package com.jjsc.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jjsc.common.core.web.controller.BaseController;
import com.jjsc.common.core.web.domain.AjaxResult;
import com.jjsc.common.core.web.page.TableDataInfo;
import com.jjsc.common.log.annotation.Log;
import com.jjsc.common.log.enums.BusinessType;
import com.jjsc.product.api.domain.Category;
import com.jjsc.product.api.domain.dto.CategoryTreeVO;
import com.jjsc.product.service.ICategoryService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: 钟城明
 * @CreateTime: 2025-10-11
 * @Description:
 * @Version: 1.0
 */
@RestController
@Tag(name = "商品分类管理")
@RequestMapping("/category")
public class CategoryController extends BaseController {

    @Autowired
    private ICategoryService categoryService;


    /**
     * 获取分类树
     */
    @GetMapping("/tree")
    public TableDataInfo getTree(Category category) {
        startPage();
        List<CategoryTreeVO> list = categoryService.getCategoryTree(category);
        return getDataTable(list);
    }

    /**
     * 新增分类
     */
    @Log(title = "商品分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Category category) {
        categoryService.addCategory(category);
        return AjaxResult.success();
    }

    /**
     * 修改分类
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Category category) {
        categoryService.updateCategory(category);
        return AjaxResult.success();
    }

    /**
     * 删除分类
     */
    @Log(title = "商品分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{categoryId}")
    public AjaxResult remove(@PathVariable Long categoryId) {
        categoryService.deleteCategory(categoryId);
        return AjaxResult.success();
    }

    /**
     * 获取分类级联选项（用于商品表单）
     */
    @GetMapping("/cascader")
    public AjaxResult getCascaderOptions() {
        List<Category> all = categoryService.list(new LambdaQueryWrapper<Category>()
                .eq(Category::getDelFlag, "0")
                .eq(Category::getStatus, "0")
                .orderByAsc(Category::getSort));

        List<Map<String, Object>> tree = buildCascaderTree(all, 0L);
        return AjaxResult.success(tree);
    }
   /* @GetMapping("/options")
    public AjaxResult getOptions() {
        List<Category> list = categoryService.list(new LambdaQueryWrapper<Category>()
                .eq(Category::getDelFlag, "0")
                .eq(Category::getStatus, "0")
                .orderByAsc(Category::getSort));
        List<Map<String, Object>> options = list.stream()
                .map(c -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("value", c.getCategoryId());
                    map.put("label", " ".repeat((c.getLevel() - 1) * 2) + c.getName());
                    return map;
                })
                .collect(Collectors.toList());
        return AjaxResult.success(options);
    }*/

    private List<Map<String, Object>> buildCascaderTree(List<Category> all, Long parentId) {
        return all.stream()
                .filter(item -> Objects.equals(item.getParentId(), parentId))
                .map(item -> {
                    Map<String, Object> node = new HashMap<>();
                    node.put("value", item.getCategoryId());
                    node.put("label", item.getName());
                    List<Map<String, Object>> children = buildCascaderTree(all, item.getCategoryId());
                    if (!children.isEmpty()) {
                        node.put("children", children);
                    }
                    return node;
                })
                .collect(Collectors.toList());
    }

}
